package com.blue.core.file.android;

import java.io.File;
import java.io.PrintWriter;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.blue.core.file.IFileHandler;

public class AndroidDocFileHandler implements IFileHandler
{
	public AndroidDocFileHandler()
	{
	}

	@Override
	public boolean accept(File file)
	{
		if (file.isDirectory())
			return true;
		
		return file.getName().endsWith(".html");
	}

	@Override
	public void handle(File file)
	{
		System.out.printf("正在处理文件：%s\n", file.getAbsolutePath());
		try
		{
			Document doc = Jsoup.parse(file, "utf-8");
			
			boolean change = false;
			
			change = this.handleNode(doc.head());
			change = this.handleNode(doc.body());
			
			if (!change)
				return;
			
			try (PrintWriter pw = new PrintWriter(file, "utf-8");)
			{
				pw.print(doc.html());
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private boolean handleNode(Element node)
	{
		if (node == null)
			return false;
		
		boolean change = false;
		Elements csss = node.select("link");
		if (csss != null)
		{
			for (Element css : csss)
			{
				String href = css.attr("href");
				if ((href.startsWith("http://") || href.startsWith("https://")) && (href.indexOf("google") != -1 || href.indexOf("android") != -1))
				{
					change = true;
					css.remove();
				}
			}
		}
		Elements jss = node.select("script");
		if (jss != null)
		{
			for (Element js : jss)
			{
				String src = js.attr("src");
				if ((src.startsWith("http://") || src.startsWith("https://")) && (src.indexOf("google") != -1 || src.indexOf("android") != -1))
				{
					change = true;
					js.remove();
				}
			}
		}
		return change;
	}
	
}
